<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <el-row>
      <el-col :span="4">
        <el-card style="width: 300px; height: 300px; color: #333">
         <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">在线用户<span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
          <div style="padding: 10px 0" v-for="user in users" :key="user.username">
            <span>{{ user }}</span>
            <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
               @click="chatUser = user"></i>
            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user === chatUser">chatting...</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="20">
        <div style="width: 800px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
          <div style="text-align: center; line-height: 50px;">
            {{ chatUser }}
          </div>
<!--          <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>-->
          <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" >
            <textarea v-model="msg" style="height: 100%; width: 100%;border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none">
            </textarea>
          </div>

          <div style="height: 200px">
            <textarea v-model="text" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none">
            </textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import request from "@/utils/request";
import axios from "axios";

let socket;

export default {
  name: "Im",
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      isCollapse: false,
      users: ["robot01"],
      chatUser: 'Code Chat',
      chatUserId: 0,
      text: '',
      msg: '',
      messages: [],
      content: '',
      username: '',
      userid: 0,
    }
  },
  created() {
    this.init()
  },
  methods: {
    send() {
      if (this.chatUser==='Code Chat') {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      }
      // 组装待发送的消息 json {"from": "zhang", "to": "admin", "text": "聊天文本"}
      // todo toId: this.chatUserId
      let message = {fromName: this.username, toName: this.chatUser, fromId: this.userid,text:this.text}
      socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
      // this.messages.push({user: this.username, text: this.text})
      // 构建消息内容，本人消息
      // this.createContent(null, this.user.username, this.text)
      this.text = '';
    },

    init() {
      this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
      console.log(this.user)
      let username = this.user.sysUser.username;
      let userid = this.user.sysUser.id;
      this.username = username;
      this.userid = userid;

      console.log(username)
      let _this = this;
      if (typeof (WebSocket) == "undefined") {
        alert("该浏览器不支持WebSocket")
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://101.43.146.76:8802/index";
        // let socketUrl = "ws://localhost:8802/index";
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          const online = {online:username};
          socket.send(JSON.stringify(online))
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {  // 获取在线人员信息
            _this.users = data.users.filter(user => user !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            console.log(data.text)
            if (data.from===_this.username && data.to===_this.chatUser){
              _this.msg = _this.msg +"\n"+ data.text;
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    }

  },
  watch: {
    chatUser: function (newValue,oldValue) {
      if (newValue !== oldValue){
        request.get("/chat/record/context/",{
          params:{
            sendName: this.username,
            receiveName: newValue
          }
        }).then(res => {
          console.log(res)
          this.msg = res.data
        })
      }
    }
  }
}

</script>

<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}

.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
